#include "RS485.h"

#define RS485_TR_TMODE (HAL_GPIO_WritePin(RS485_TR_GPIO_Port,RS485_TR_Pin,GPIO_PIN_SET))
#define RS485_TR_RMODE (HAL_GPIO_WritePin(RS485_TR_GPIO_Port,RS485_TR_Pin,GPIO_PIN_RESET))

//读取指令                    0x03, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC5, 0xE9
static uint8_t cmdBuff[8] = {0x03, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC5, 0xE9};
static uint8_t cmdBuffLen = 8;

//rs485返回数据缓存区
uint8_t TemDataBuff[9]; //接收数据缓存区
uint16_t TemDataBufflen = 0; // 缓存区数据长度

uint16_t temOld; //处理前的温度湿度数据
uint16_t humOld;

float temNew;  // /处理后的温度湿度数据
float humNew;

void RS485_ReadData(void)
{
    // 每次读取前 清空缓冲数组  避免上次数据影响
    memset(TemDataBuff,0,sizeof(TemDataBuff));

	//1.stm32请求读取
	RS485_TR_TMODE; //RS485 串口为发送模式
	HAL_UART_Transmit(&huart2,cmdBuff,cmdBuffLen,4000); //stm32发送读取命令
	RS485_TR_RMODE; //RS485 串口为接收模式
    HAL_UARTEx_ReceiveToIdle_IT(&huart2, TemDataBuff,9); //接收RS485返回的应答数据  接收数据 高位在前
    HAL_Delay(20);
	//得到RS485返回的没处理的温度湿度
	temOld = TemDataBuff[3] << 8 | TemDataBuff[4];  //如0X01 0X03合在一起表示一个温度数据 假如为282
	humOld = TemDataBuff[5] << 8 | TemDataBuff[6];
    HAL_Delay(20);
    // 处理为真实 可读数据
    temNew = (float)temOld / 10.0;  //这里在282/10=28.2 真实温度 
    humNew = (float)humOld / 10.0;
    printf("Temperature:%f\r\n",temNew);
    printf("Humidity:%f\r\n",humNew);
    HAL_Delay(20);
}




